<template>
	<view class="almost-lottery">
		<view class="dynbg">
			<view class="dynbg__bg dynbg__bg0"></view>
			<view class="dynbg__bg dynbg__bg1"></view>
			<view class="dynbg__bg dynbg__bg2"></view>
			<view class="dynbg__bg dynbg__bg3"></view>
			<view class="dynbg__bg dynbg__bg4"></view>
		</view>

		<!-- head -->
		<!-- 		<view class="almost-lottery__head">
			<view :class="['action', isApple && 'action-shadow']">
				<text class="gold"></text>
				<text class="content">
					金币余额：
					<text class="num">{{ goldCoin }}</text>
				</text>
			</view>
			<view class="tip">
				<text class="tip-content">每次抽奖消耗 {{ goldNum }} 金币，不限次数</text>
			</view>
		</view> -->
		<!-- action -->
		<view class="almost-lottery__action-dev" @tap="handleInitCanvas" v-if="isDev"><text
				class="text">重新生成画板-开发模式使用</text></view>
		<!-- lottery -->
		<view class="almost-lottery__wheel">
			<almost-lottery :lottery-size="lotteryConfig.lotterySize" :action-size="lotteryConfig.actionSize"
				:ring-count="2" :duration="1" :prize-list="prizeList" :prize-index="prizeIndex"
				@reset-index="prizeIndex = -1" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
				@finish="handleDrawFinish" v-if="prizeList.length" />
			<view class="almost-lottery__count">
				<text class="text">剩余免费抽奖 {{ freeNum }} 次</text>
			</view>
		</view>
		<!-- rule -->
		<view class="almost-lottery__rule">
			<view class="rule-head">
				<view class="line"></view>
				<text class="title">活动规则</text>
				<view class="line"></view>
			</view>
			<view class="rule-body">
				<view class="item">
					<view class="number">1</view>
					<view class="text">
						<text>抽奖细则：</text>
						<text>每人每天拥有{{ freeNumDay }}次抽奖机会。</text>
					</view>
				</view>
				<view class="item">
					<view class="number">2</view>
					<view class="text">本次活动由六折电影票发起，最终解释权归灵智天成科技有限公司所有。</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Route from '../../utils/route.js';
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue';
	import {
		clearCacheFile
	} from '@/uni_modules/almost-lottery/utils/almost-utils.js';
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				// 开启调试模式
				isDev: false,
				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 200
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				lotteryBg: '',
				// 抽奖按钮图
				actionBg: '',

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: true,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: false,
				// 权重随机数的最大值
				prizeWeightMax: 0,
				// 权重数组
				prizeWeightArr: [],

				// 以下为业务需求有关示例数据
				// 金币余额
				goldCoin: 888,
				// 当日免费抽奖次数余额
				freeNum: 1,
				// 每次消耗的金币数
				goldNum: 999,
				// 每天免费抽奖次数
				freeNumDay: 1
			};
		},
		computed: {
			isApple() {
				return uni.getSystemInfoSync().platform === 'ios';
			}
		},
		methods: {
			// 重新生成
			handleInitCanvas() {
				clearCacheFile();
				this.prizeList = [];
				this.getPrizeList();
			},
			// 获取奖品列表
			async getPrizeList() {
				uni.showLoading({
					title: '奖品准备中...'
				});

				let data = await Route.wheel_prize_list();
				for (var i = 0; i < data.length; i++) {
					data[i].prizeId = data[i].id;
					data[i].prizeName = data[i].name;
					data[i].prizeStock = data[i].stock;
					data[i].prizeWeight = data[i].weight;
					data[i].prizeImage = data[i].image || '';
				}
				if (data.length) {
					this.prizeList = data;

					// 如果开启了前端控制概率
					// 得出权重的最大值并生成权重数组
					if (this.onFrontend) {
						// 生成权重数组并排序取得最大值
						this.prizeWeightArr = this.prizeList.map(item => item.prizeWeight);
						let prizeWeightArrSort = [...this.prizeWeightArr];
						prizeWeightArrSort.sort((a, b) => b - a);

						// 开放自定义权重最大值，没有自定义则取权重数组中的最大值
						this.prizeWeightMax = this.prizeWeightMax > 0 ? this.prizeWeightMax : prizeWeightArrSort[0];
					}
				}
			},

			// 本次抽奖开始
			handleDrawStart() {
				if (this.prizeing) return;
				this.prizeing = true;

				// 还有免费数次或者剩余金币足够抽一次
				if (this.freeNum > 0 || this.goldCoin >= this.goldNum) {
					// 更新免费次数或金币余额
					if (this.freeNum > 0) {
						this.freeNum--;
					} else if (this.goldCoin >= this.goldNum) {
						this.goldCoin -= this.goldNum;
					}

					this.tryLotteryDraw();
				} else {
					this.prizeing = false;
					uni.showModal({
						title: '余额不足',
						content: '请明日再来',
						success: res => {
							// 这里需要根据业务需求处理，一般情况下会引导用户前往赚取金币的页面
						}
					});
				}
			},
			// 尝试发起抽奖
			tryLotteryDraw() {
				// 判断是否由前端控制概率
				if (this.onFrontend) {
					this.localGetPrizeIndex();
				} else {
					this.remoteGetPrizeIndex();
				}
			},
			// 本地获取中奖下标
			localGetPrizeIndex() {
				console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###');
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (!this.prizeWeightMax || !this.prizeWeightArr.length) {
					console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 prizeWeight 参数似乎配置不正确###');
					return;
				}

				// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
				let randomWeight = Math.ceil(Math.random() * this.prizeWeightMax);

				// 生成大于等于随机权重的数组
				let tempMaxArrs = [];
				this.prizeList.forEach(item => {
					if (item.prizeWeight >= randomWeight) {
						tempMaxArrs.push(item.prizeWeight);
					}
				});

				// 如果大于随机权重的数组有值，先对这个数组排序然后取值
				// 反之新建一个临时的包含所有权重的已排序数组，然后取值
				let tempMaxArrsLen = tempMaxArrs.length;
				if (tempMaxArrsLen) {
					tempMaxArrs.sort((a, b) => a - b);
					// 取值时，如果存在多个值，分两种情况
					if (tempMaxArrsLen > 1) {
						// 检查是否存在重复的值
						let sameCount = 0;
						for (let i = 0; i < tempMaxArrs.length; i++) {
							if (tempMaxArrs[i] === tempMaxArrs[0]) {
								sameCount++;
							}
						}

						// 值不相等的情况下取最接近的值，也就是第1个值
						if (sameCount === 1) {
							this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0]);
						} else {
							// 存在值相等时，随机取值，当然这里你可以自己决定是否随机取值
							let sameWeight = tempMaxArrs[0];
							let sameWeightArr = [];
							let sameWeightItem = {};
							this.prizeWeightArr.forEach((item, index) => {
								if (item === sameWeight) {
									sameWeightArr.push({
										prizeWeight: item,
										index
									});
								}
							});
							sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)];
							this.prizeIndex = sameWeightItem.index;
						}
					} else {
						this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0]);
					}
				}


				// 如果奖品设有库存
				if (this.onStock) {
				}
			},

			async remoteGetPrizeIndex() {
				let list = [...this.prizeList];

				// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
				let prizeId = Math.floor(Math.random() * list.length + 1);

				// 拿到后端返回的 prizeId 后，开始循环比对得出那个中奖的数据
				for (let i = 0; i < list.length; i++) {
					let item = list[i];
					if (item.prizeId === prizeId) {
						// 中奖下标
						this.prizeIndex = i;
						break;
					}
				}


				if (this.prizeList[this.prizeIndex].prizeName != '谢谢参与') {
					await Route.wheel_prize_get({
						prizeId: this.prizeList[this.prizeIndex].prizeId,
						uid: uni.getStorageSync('userInfo').uid
					});
				}

				// 如果奖品设有库存
				if (this.onStock) {
				}
			},
			// 本次抽奖结束
			async handleDrawEnd() {
				// 旋转结束后，开始处理拿到结果后的逻辑
				this.prizeing = false;
				let prizeName = this.prizeList[this.prizeIndex].prizeName;
				let tipContent = '';

				if (prizeName === '谢谢参与') {
					tipContent = '很遗憾，没有中奖，请再接再厉！';
				} else {
					// 如果奖品设有库存
					if (this.onStock) {
						let prizeStock = this.prizeList[this.prizeIndex].prizeStock;
						tipContent = prizeStock ? `恭喜您，获得 ${prizeName}` : `很抱歉，您来晚了，当前奖品 ${prizeName} 已无库存`;
					} else {
				
						tipContent = `恭喜您，获得 ${prizeName} ！`;
					}
				}

				uni.showModal({
					content: tipContent,
					showCancel: false
				});
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				let stoTimer = setTimeout(() => {
					clearTimeout(stoTimer);
					stoTimer = null;
					uni.showToast({
						title: res.msg,
						mask: true,
						icon: 'none'
					});
				}, 50);
			}
		},
		async onLoad() {
			let res = await Route.wheel_prize_info({
				uid: uni.getStorageSync('userInfo').uid
			})
			if (res) {
				uni.showModal({
					content: '今日已抽奖,请明日再来',
					showCancel: false,
				 success: function(res) {
						uni.switchTab({
							url: '../index/index'
						})
					}

				});
			}
			this.handleInitCanvas();
		},
		onUnload() {
			uni.hideLoading();
		}
	};
</script>

<style lang="scss" scoped>
	.almost-lottery {
		width: 100vw;
		height: 100vh;
		// background: -moz-radial-gradient(80% 20%, farthest-side, #edbf47, #d58123);
		// background: -webkit-radial-gradient(80% 20%, farthest-side, #edbf47, #d58123);
	}

	.dynbg {
		position: absolute;
		z-index: -1;
		top: 0px;
		left: 0px;
		width: 100vw;
		height: 100vh;
	}

	.dynbg__bg {
		position: absolute;
		top: 0px;
		left: 0px;
		-webkit-transition: all 1s linear;
		-moz-transition: all 1s linear;
		width: 100vw;
		height: 100vh;
		background-size: 100% 100%;
	}

	.dynbg__bg0 {
		background-repeat: repeat;
		background: -webkit-radial-gradient(rgba(255, 255, 255, 0.4) 5%, transparent 10%);
		background: -moz-radial-gradient(rgba(255, 255, 255, 0.4) 5%, transparent 10%);
		background-size: 16px 16px;
		z-index: 5;
	}

	.dynbg__bg1 {
		background: -moz-radial-gradient(80% 20%, farthest-side, #edbf47, #d58123);
		background: -webkit-radial-gradient(80% 20%, farthest-side, #edbf47, #d58123);
		z-index: 4;
		-webkit-animation: dynbg__ani1 infinite 8s;
		-moz-animation: dynbg__ani1 infinite 8s;
	}

	.dynbg__bg2 {
		background: -moz-radial-gradient(80% 80%, farthest-side, #edbf47, #d58123);
		background: -webkit-radial-gradient(80% 80%, farthest-side, #edbf47, #d58123);
		z-index: 3;
		-webkit-animation: dynbg__ani2 infinite 8s;
		-moz-animation: dynbg__ani2 infinite 8s;
	}

	.dynbg__bg3 {
		background: -moz-radial-gradient(20% 80%, farthest-side, #edbf47, #d58123);
		background: -webkit-radial-gradient(20% 80%, farthest-side, #edbf47, #d58123);
		z-index: 2;
		-webkit-animation: dynbg__ani3 infinite 8s;
		-moz-animation: dynbg__ani3 infinite 8s;
	}

	.dynbg__bg4 {
		background: -moz-radial-gradient(20% 20%, farthest-side, #edbf47, #d58123);
		background: -webkit-radial-gradient(20% 20%, farthest-side, #edbf47, #d58123);
		z-index: 1;
	}

	@-webkit-keyframes dynbg__ani1 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 0;
		}

		33.3333% {
			opacity: 0;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 0;
		}

		83.3333% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}

	@-webkit-keyframes dynbg__ani2 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 1;
		}

		33.3333% {
			opacity: 0;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 0;
		}

		83.3333% {
			opacity: 1;
		}

		100% {
			opacity: 1;
		}
	}

	@-webkit-keyframes dynbg__ani3 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 1;
		}

		33.3333% {
			opacity: 1;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 1;
		}

		83.3333% {
			opacity: 1;
		}

		100% {
			opacity: 1;
		}
	}

	@-moz-keyframes dynbg__ani1 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 0;
		}

		33.3333% {
			opacity: 0;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 0;
		}

		83.3333% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}

	@-moz-keyframes dynbg__ani2 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 1;
		}

		33.3333% {
			opacity: 0;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 0;
		}

		83.3333% {
			opacity: 1;
		}

		100% {
			opacity: 1;
		}
	}

	@-moz-keyframes dynbg__ani3 {
		0% {
			opacity: 1;
		}

		16.6667% {
			opacity: 1;
		}

		33.3333% {
			opacity: 1;
		}

		50% {
			opacity: 0;
		}

		66.6667% {
			opacity: 1;
		}

		83.3333% {
			opacity: 1;
		}

		100% {
			opacity: 1;
		}
	}

	.almost-lottery__head {
		position: relative;
		width: 100%;

		.action {
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 480rpx;
			height: 88rpx;
			line-height: 88rpx;
			margin: 0 auto;
			color: #ffffff;
			font-size: 32rpx;
			background-color: rgba(255, 136, 61, 1);
			border-radius: 44rpx;
		}

		.action-shadow {
			box-shadow: 0px 14rpx 0px 0px rgba(235, 112, 36, 1);
		}

		.gold {
			width: 44rpx;
			height: 44rpx;
			margin-right: 10rpx;
			background-repeat: no-repeat;
			background-position: center center;
			background-size: contain;
			background-image: url('~static/images/lottery/gold.png');

			@media (-webkit-min-device-pixel-ratio: 2),
			(min-device-pixel-ratio: 2) {
				background-image: url('~static/images/lottery/gold@2x.png');
			}

			@media (-webkit-min-device-pixel-ratio: 3),
			(min-device-pixel-ratio: 3) {
				background-image: url('~static/images/lottery/gold@3x.png');
			}
		}

		.num {
			color: #f9fc31;
		}

		.tip {
			position: relative;
			top: 428rpx;
			color: #ffffff;
			font-size: 24rpx;
			text-align: center;
		}
	}

	.almost-lottery__wheel {
		text-align: center;
	
	.almost-lottery__count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			text-align: center;
			padding: 40rpx 0;
		}

		.text {
			color: #ffffff;
			font-size: 24rpx;
		}
	}

	.almost-lottery__rule {
		padding: 0 28rpx;
		color: #fff8cb;

		.rule-head {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 40rpx 0;

			.line {
				flex: 1;
				height: 1px;
				background-color: #fff3a5;
			}

			.title {
				width: 280rpx;
				color: #f63857;
				line-height: 70rpx;
				text-align: center;
				margin: 0 20rpx;
				border-radius: 8rpx;
				background-image: linear-gradient(0deg, rgba(255, 242, 158, 1), rgba(255, 244, 168, 1));
			}
		}

		.rule-body {
			color: #fff8cb;
			font-size: 24rpx;
			padding: 10rpx 0 40rpx;

			.item {
				display: flex;
				margin-bottom: 10rpx;
			}

			.number {
				position: relative;
				top: 4rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				color: #f63857;
				background: #fff8cb;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.text {
				flex: 1;
			}

			.item-rule .text {
				display: flex;
				flex-direction: column;
			}
		}
	}

	.almost-lottery__action-dev {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		width: 400rpx;
		height: 80rpx;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto 40rpx;

		.text {
			color: #ffffff;
			font-size: 28rpx;
		}
	}
</style>
